package vip.xumy.admin.utils;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.log4j.Log4j2;
import vip.xumy.admin.sys.pojo.ActionLog;
import vip.xumy.admin.sys.service.LogService;
import vip.xumy.core.utils.StringUtil;

@Log4j2
public class BaseLogUtil {
	public static LogService logService;

	protected BaseLogUtil() {
		// Add a protected constructor to hide the implicit public one.
	}

	/**
	 * 获取访问者IP
	 * 
	 * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
	 * 
	 * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)， 如果还不存在则调用Request
	 * .getRemoteAddr()。
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (!StringUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		} else {
			return request.getRemoteAddr();
		}
	}

	public static ActionLog createLog(HttpServletRequest request, String module, String type) {
		ActionLog log = new ActionLog();
		log.setLoginIp(getIpAddr(request));
		log.setUserId(LoginUtil.getUserId(request));
		log.setModule(module);
		log.setType(type);
		return log;
	}

	protected static void logToFileAndDatabase(ActionLog actionLog) {
		log.info(MessageFormat.format("{0}-------操作用户:{1},{2}", logService.getTypeMap().get(actionLog.getType()),
				actionLog.getUserId(), actionLog.getContext()));
		logService.insertActionLog(actionLog);
	}

}
